package org.sraosha.framework.util;

//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @desc   日常工具类
 */
public final class MiscUtil {
//    private static final Logger LOGGER = LoggerFactory.getLogger(MiscUtil.class);

    /**
     * 判断两个时间是否在相差的分钟数之内
     * @param startDate 起始时间
     * @param endDate 结束
     * @param smsCodeValidTime 相差的分钟数
     * @return 返回比较结果
     */
    public static boolean checkValidTime(Date startDate, Date endDate, int smsCodeValidTime) {
        long start = startDate.getTime();
        long end = endDate.getTime();
        return compareDate(start, end, smsCodeValidTime);
    }

    /**
     * 判断两个时间是否在相差的分钟数之内
     * @param start 起始时间
     * @param end 结束时间
     * @param smsCodeValidTime 相差的分钟数
     * @return 返回比较结果
     */
    private static boolean compareDate(long start, long end, int smsCodeValidTime) {
        int mm = (int) (end - start) / 1000 / 60;
        return mm <= smsCodeValidTime;
    }

    /**
     * 按照length生成随机数
     * @param length 随机数的长度/位数
     * @return 返回结果
     */
    public static String randomNum(int length) {
        String seed = "0123456789";

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(seed.charAt(ThreadLocalRandom.current().nextInt(seed.length())));
        }
        return sb.toString();
    }

    /**
     * 按照length生成随机字符
     * @param length 随机数的长度/位数
     * @return 返回结果
     */
    public static String randomChar(int length) {
        String seed = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < length; i++) {
            sb.append(seed.charAt(ThreadLocalRandom.current().nextInt(seed.length())));
        }
        return sb.toString();
    }

    /**
     * @param length    长度
     * @param algorithm 常用算法：SHA1PRNG
     * @return
     */
    public static String randomNum(int length, String algorithm) {
        SecureRandom random = null;
        try {
            random = SecureRandom.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
//            LOGGER.error("生成密钥异常: " + e.getMessage(), e);
            throw new IllegalArgumentException();
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(9));
        }
        return sb.toString();
    }

    public static String qrCodeNonceStr() {
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 24; ++i) {
            int number = ThreadLocalRandom.current().nextInt(36);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    public static String formatClearDate(Date clearDate) {
        return MessageFormat.format("{0,date,yyyy-MM-dd}", clearDate);
    }

    public static String toStringAndTrim(Object object) {
        if (object == null) {
            return "";
        } else {
            return object.toString().trim();
        }
    }

    /**
     * 判断输入的字符串是否是空
     *
     * @param inStr 输入字符串
     * @return
     */
    public static boolean isNullOrEmpty(String inStr) {
        return (inStr == null || inStr.trim().length() == 0);
    }

    /**
     * 判断输入的字符串是否是空
     *
     * @param object 输入字符串
     * @return
     */
    public static boolean isNullOrEmpty(Object object) {
        return (object == null) || object.toString().trim().length() == 0;
    }

    /**
     * 将日期格式化为字符串 yyyyMMddHHmmss
     *
     * @param date
     * @return
     */
    public static String timeToString(Date date) {
        if (date == null){
            return "";
        }
        return new SimpleDateFormat("yyyyMMddHHmmss").format(date);
    }


    /**
     * 利用java原生的类实现SHA256加密
     *
     * @param str 加密后的报文
     * @return
     */
    public static String getSHA256(String str) {
        System.out.println(str);
        MessageDigest messageDigest;
        String encodestr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodestr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(encodestr);
        return encodestr;
    }

    /**
     * 将byte转为16进制
     *
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                // 1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

    /**
     * 获取现在时间
     *
     * @return返回字符串格式 yyyyMMddTHHmmss
     */
    public static String getStringDate(Date clearDate) {
        Date currentTime = clearDate;
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat formatter2 = new SimpleDateFormat("HHmmss");
        String dateString = formatter1.format(currentTime)+"T"+formatter2.format(currentTime);
        return dateString;
    }
}